<script setup lang="ts">
import usePaperStore from "../../store/paperStore.ts";
import { useRouter } from "vue-router";
import { Answer, AnswerItem, Paper } from "../../index";
import XzItem from "../../components/exam/XzItem.vue";
import PdItem from "../../components/exam/PdItem.vue";
import TkItem from "../../components/exam/TkItem.vue";
import { ElMessage } from "element-plus";
import { submitPaperAPI } from "../../api/paper.ts";

const paperStore = usePaperStore();

const answers: Answer[] = [];
const router = useRouter();

const paper: Paper | null = paperStore.getPaper;
if (paper === null) {
  router.push({ name: "exam_prepare" });
}

const addAnswer = (item: AnswerItem) => {
  const flag = answers.find((t) => {
    const flag = t.questionID === item.questionID;
    if (flag) {
      t.content = item.content;
    }
    return flag;
  });
  if (!flag) answers.push({ ...item, paperID: (paper as Paper).id });
  // console.log(answers);
};

const submitPaper = () => {
  submitPaperAPI(answers)
    .then((response) => {
      if (response.status !== 200) {
        throw new Error("网络错误");
      }
      return response.data;
    })
    .then((result) => {
      ElMessage({
        message: JSON.stringify(result.data),
      });
      router.push({ name: "exam_history" });
    });
};
</script>

<template>
  <el-card class="lg:mx-56 lg:my-4 paper" v-if="paper">
    <img
      class="paper-background"
      src="../../assets/image/xiaohui.png"
      alt="校徽"
    />
    <div class="p-16 text-4xl">{{ paper.title }}</div>
    <div>
      <el-form>
        <div class="p-2">
          <div class="title">选择题</div>
          <div v-for="(xz, index) in paper.xzQuestions" :key="xz.id">
            <XzItem @hasAnswer="addAnswer" :xz="xz" :index="index" />
          </div>
        </div>
        <div class="p-2">
          <div class="title">判断题</div>
          <div v-for="(pd, index) in paper.pdQuestions" :key="pd.id">
            <PdItem @hasAnswer="addAnswer" :pd="pd" :index="index" />
          </div>
        </div>
        <div class="p-2">
          <div class="title">填空题</div>
          <div v-for="(tk, index) in paper.tkQuestions" :key="tk.id">
            <TkItem @hasAnswer="addAnswer" :tk="tk" :index="index" />
          </div>
        </div>
        <div class="py-5 mb-3">
          <el-button type="primary" class="float-right" @click="submitPaper"
            >提交试卷
          </el-button>
        </div>
      </el-form>
    </div>
  </el-card>
</template>

<style>
.title {
  @apply text-3xl p-2 text-center mb-2 text-blue-800;
}

.question-title {
  @apply p-1 m-3 text-zinc-950;
}

.paper {
  position: relative;
}

.paper-background {
  position: absolute;
  width: 20%;
  transform: translate(420%, -30%);
  opacity: 0.2;
}

.question-content {
  @apply p-4;
}
</style>
